import { ref } from "vue";
import { httpAxios } from ".";
import { httpSetting } from "@/config";

type ReqFuc<T, V> = (
  params: T,
  config: AxionsOptions.RequestConfig
) => Promise<Result<V>>;



export const request = {

  execute<T, V>(
    method: ReqFuc<T, V>,
    url: string,
    params: T,
    option: AxionsOptions.RequestConfig
  ) {
    let opt = Object.assign({}, httpSetting, option);
    opt.url = url;

    let loading = ref<boolean>(false);

    let run: RequestCb<V> = (onSuccess, onFail, onComplete) => {
      loading.value = true;
      method(params, opt)
        .then((res) => {
          onSuccess?.(res);
        })
        .catch((err) => {
          onFail?.(err);
        })
        .finally(() => {
          loading.value = false;
          onComplete?.();
        });
    };

    return {
      loading,
      params,
      run,
    };
  },

  //请求方法
  get<T = any, V = any>(
    url: string,
    params: T,
    options: AxionsOptions.RequestOptions = {}
  ) {
    return this.execute<T, V>(
      httpAxios.get.bind(httpAxios),
      url,
      params,
      options
    );
  },

  post<T = any, V = any>(
    url: string,
    params: T,
    options: AxionsOptions.RequestOptions = {}
  ) {
    return this.execute<T, V>(
      httpAxios.post.bind(httpAxios),
      url,
      params,
      options
    );
  },

  put<T = any, V = any>(
    url: string,
    params: T,
    options: AxionsOptions.RequestOptions = {}
  ) {
    return this.execute<T, V>(
      httpAxios.put.bind(httpAxios),
      url,
      params,
      options
    );
  },

  delete<T = any, V = any>(
    url: string,
    params: T,
    options: AxionsOptions.RequestOptions = {}
  ) {
    return this.execute<T, V>(
      httpAxios.delete.bind(httpAxios),
      url,
      params,
      options
    );
  }

}